﻿<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <title></title>
    </head>
    <body>

    </body>
</html>
<script>
    /*****************************************/
    //Explanation of Combination Constructor/Prototype Pattern
    /*****************************************/
    function User(theName, theEmail) {
        //The following lines initialize the instance properties
        // The use of the the this keyword inside the function specifies that these properties will be unique to every instance of the User object:
        this.name = theName;
        this.email = theEmail;
        this.quizScores = [];
        this.currentScore = 0;
    }

    User.prototype = {//we are overwriting the prototype property with an object literal so we don’t have to write User.prototype each time
        constructor: User, //The one disadvantage of overwriting the prototype is that the constructor property no longer points to the prototype, so we have to set it manually
        saveScore: function(theScoreToAdd) {
            this.quizScores.push(theScoreToAdd);
        },
        showNameAndScores: function() {
            var scores = this.quizScores.length > 0 ? this.quizScores.join(",") : "No Scores Yet";
            return this.name + " Scores: " + scores;
        },
        changeEmail: function(newEmail) {
            this.email = newEmail;
            return "New Email Saved: " + this.email;
        }
    };


    /*****************************************/
    //Inheritance in JavaScript (The Best Pattern: Parasitic Combination Inheritance)
    /*****************************************/
    // We have a simple cars object
    var cars = {
        type: "sedan",
        wheels: 4
    };

    // We want to inherit from the cars object, so we do:
    var toyota = Object.create(cars); // now toyota inherits the properties from cars
    console.log(toyota.type); // sedan

    //otro ejemplo
    //------------
    function inheritPrototype(childObject, parentObject) {
        // As discussed above, we use the Crockford’s method to copy the properties and methods from the parentObject onto the childObject
        // So the copyOfParent object now has everything the parentObject has 
        var copyOfParent = Object.create(parentObject.prototype);

        //Then we set the constructor of this new object to point to the childObject.
        //This step is necessary because the preceding step overwrote the childObject constructor when it overwrote the childObject prototype (during the Object.create() process)
        copyOfParent.constructor = childObject;

        // Then we set the childObject prototype to copyOfParent, so that the childObject can in turn inherit everything from copyOfParent (from parentObject)
        childObject.prototype = copyOfParent;
    }
</script>
